<template>
  <div class="add-playlist">
    <van-popup class=" h-1/2 " v-model:show="store.addPlaylistPopup" :class="store.isFlag ? 'w-1/3' : 'w-3/4'">
      <div class="z-50 h-10 yu-bgColor-active  flex flex-col justify-center sticky top-0 pl-2">添加到歌单</div>
      <div class="h-13 yu-bgColor-one-only yu-textColor-hover flex items-center pl-2 cursor-pointer"  @click="setNewSongListPopup">
        <van-icon class-prefix="i-mdi-gamepad-round"/>
        <span class="ml-1">新建歌单</span>
      </div>
      <div class="pl-3 yu-bgColor-tew-only">
        <span class="block h-15 flex items-center cursor-pointer yu-textColor-hover"
              v-for="playlist in playlists"
              :key="playlist.id"
              @click="setPlaylistTracks(playlist.id)"
        >
          <span class="w-10 h-10">
            <img class="w-full h-full" :src="playlist.coverImgUrl" alt=""/>
          </span>
          <span class="flex flex-col ml-2 justify-between  text-sm">
            <span>{{ playlist.name }}</span>
            <span>{{ playlist.trackCount }}首</span>
          </span>
        </span>
      </div>
    </van-popup>
    <!-- 新建歌单弹窗 -->
    <new-song-list @newAddMusic="newAddMusic"/>
  </div>
</template>

<script setup>
// vue
import {onMounted, reactive, toRefs } from "vue";
// pinia
import {useStore} from "@/store/index"
// vant
import {Notify} from "vant";
// api
import {getUserPlaylist, getPlaylistTracks} from "@/api/login/index";
// 组件
import NewSongList from '@/components/NewSongList/index.vue'
const store = useStore()
const addMyMusicReactive = reactive({
  playlists: []
})
onMounted(() => {
  // 渲染完成之后调用
  getUserPlaylistA()
})
// 获取我的歌单
const getUserPlaylistA = () => {
  // uid可以随便传递由于由于传递了token有了身份
  getUserPlaylist({uid: 0}).then(res => {
    const {code, playlist} = res
    if (Number(code) === 200) {
      addMyMusicReactive.playlists = playlist
    }
  })
}

// 点击歌单添加
const setPlaylistTracks = (pid) => {
  getPlaylistTracks({ op: 'add', pid, tracks: store.musicId}).then().catch(err => {
    store.addPlaylistPopup = false
    if (err.body.code === 200) {
      Notify({
        background: 'black',
        color: 'white',
        message: '添加成功',
        duration: 3000,
      })
    } else if (err.body.code === 502 || err.body.code === 400) {
      Notify({
        background: 'red',
        message: err.body.message,
        duration: 3000,
      })
    }
    // 更新一下我的收藏列表
    getUserPlaylistA()
  })
}
// 点击新建歌单弹出新建歌单弹窗和关闭我的歌单列表弹窗
const setNewSongListPopup = () => {
  store.addPlaylistPopup = false
  store.newSongListPopup = true
}
// 新建歌单的时候是否需要添加歌曲通过传递的id判断
const newAddMusic = (id) => {
  // 不存在id就不需要调用这个
  if (store.musicId) {
    setPlaylistTracks(id)
  }
  // 关闭新建歌单弹窗
  store.newSongListPopup = false
}

const {playlists} = toRefs(addMyMusicReactive)
</script>

<style scoped>

</style>
